<!--
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-08-08 14:55:13
 * @LastEditTime : 2020-01-14 14:44:12
 * @LastEditors  : Please set LastEditors
 -->
<style scoped>
.headerBtn{
    text-align: left;
    margin: 15px 0;
}
.pageStyle{
    text-align:right;
    float:right;
}
.ivu-table-wrapper{
    overflow:visible
}
.pageStyleVm{
    text-align: center;
}
table .ivu-poptip-confirm .ivu-poptip-body .ivu-icon{
    left: 11px
}
.position_i{
    position: relative;
    top: -1px;
    margin-right: 5px
}
/* td{
    border-right: 0 !important
} */
.ivu-table-tip{
    overflow: hidden !important;
}
.starlet{
    color: red;
    position: absolute;
    left: -60px;
    font-size: 18px;
    line-height: 38px;
    font-weight: 800;
}
.zIndexStyleBtn{
    position:relative;
    z-index:55
}
ul li{
    list-style: none
}
._dot{
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #f90;
    margin-right: 5px
}
</style>
<style>
	.btnCenter .ivu-poptip-confirm .ivu-poptip-body{
		text-align:left;
	}
</style>
<template>
    <search-table
	    ref="searchTable"
		:columns="taskCol" 
        :data="taskData"
		:total="taskTotal"
		:page.sync="taskCurrentPage"
		:size.sync="taskItemPage"
		@change-size="switchTaskItemPage"
		@change-page="switchineTaskCurrentPage"
	>
    <Alert type="warning" show-icon style="margin-top: 15px;" v-if="configMode !== 1" slot="alert">
        <p style="color:#f90">配置报告持续提交需要满足的条件：</p>
        <p>1、创建“报告持续提交”任务之前，一定要在“演练目标配置”中“导入目标”</p>
        <!-- 众测演练 没有目标方管理员-->
        <p v-if="curPath && curPath.indexOf('zcDrill')<0">2、创建“报告持续提交”任务时，一定要给“目标方管理员组”添加上此任务</p>
    </Alert>
    <template slot="search">
        <Button type="primary" ghost @click="createFlagTask" class="zIndexStyleBtn" 
        v-if="configMode !== 1" :disabled="disabledAllBtn"><Icon type="ios-add" :size="16" class="position_i"/>添加任务</Button>
    <!--<Button type="primary" @click="configerManage" class="zIndexStyleBtn"><Icon type="md-settings" :size="16" class="position_i"/>配置管理</Button>--> 
    </template>
    <Modal
            v-model="createFlagTaskModal"
            title="报告持续提交"
            ok-text = "确定"
            :loading = createFlagTaskModalLoading
            width=600
            @on-ok="ok"
            @on-cancel="cancel">
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
                <FormItem label="名字" prop="name">
                    <Input v-model.trim="formValidate.name" placeholder="请输入名称" clearable :maxlength="64"></Input>
                </FormItem>
                <!--<FormItem label="类型" prop="taskMode">
                    <RadioGroup v-model="formValidate.taskMode">
                        <Radio label="normal" :disabled="disabledTepBol">流程任务</Radio>
                        <Radio label="preset" :disabled="disabledTepBol">预设临机任务</Radio>
                        <Radio label="temp" :disabled="!disabledTepBol">实时任务</Radio>
                    </RadioGroup>
                </FormItem>-->
                <FormItem label="裁判">
                    <Select filterable v-model="formValidate.referee" filterable   multiple clearable placeholder="请选择裁判">
                        <Option v-for="(item,index) in companyUsers" :key="index" :value="item.id"
                             :title="`${item.nickname}--${item.username}`">{{item.nickname+'--'+item.username}}</Option>
                    </Select>
                </FormItem>
                <FormItem label="接入组" prop="group">
                    <Select filterable v-model="formValidate.group" filterable  multiple  clearable placeholder="请选择接入组" @on-change="getAccessGroupMember">
                        <Option v-for="(item,index) in accessGroupList" :key="index" :value="item.id" :label="item.name" :title="item.name">{{item.name}}</Option>
                    </Select>
                </FormItem>
                <FormItem label="描述" prop="desc" style="margin-top:10px">
                    <Input v-model.trim="formValidate.desc" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入内容" clearable :maxlength="200"></Input>
                </FormItem>
                <!--<FormItem v-model="formValidate.selectedVmData"  label="人员">
                    <span class="starlet" style="left:-70px">*</span>
                    <input type="hidden" >
                    <Tag v-for="item in formValidate.selectedVmData" :key="item.id" :name="item.id" closable @on-close="handleClose2" color="primary" type='dot' >{{ item.name }}</Tag>
                </FormItem>-->
                <!--<FormItem label="人员" prop="peopleValue">-->
                    <!-- <Cascader :data="vmAttributeData"   placeholder="请选择人员" multiple v-model="peopleValue"></Cascader>  -->
                    <!-- <cascaderMulti :data="vmAttributeData"   placeholder="请选择人员" multiple v-model="peopleValue"></cascaderMulti>  -->
                    <!--<Select filterable v-model="peopleValue" filterable   clearable placeholder="请选择人员" multiple>
                        <Option v-for="(item,index) in vmAttributeData" :key="item.userId" :value="item.id+','+item.userId" >{{item.name}} - {{item.userName}}</Option>
                    </Select>
                </FormItem>-->
                <!--<FormItem label="子网络" prop="way">
                     <Select filterable v-model="networkArr" filterable   multiple clearable placeholder="请选择子网络" @on-change="changeNetwork">
                        <Option v-for="(item,index) in subnetList" :key="index" :value="item.id" >{{item.name}}</Option>
                    </Select>
                </FormItem>-->
                <!--<FormItem label="设备" prop="way">
                     <Select filterable v-model="currentDevice" filterable   clearable placeholder="请选择设备" multiple>
                        <Option v-for="(item,index) in dataVmList" :key="index" :value="item.id" >{{item.name}}</Option>
                    </Select>
                </FormItem>-->
                <!--<FormItem style="text-align:center">
                     <Button @click="commitTask"   long type="warning" ghost>确定</Button>
                </FormItem>-->
                <!-- <div style="text-align:right">
                    <Button type="primary" @click="addSelectedData" style="margin-right:17px">添加</Button>
                    <Input placeholder="请输入名称" style="width: 210px" v-model="formValidate.vmName" clearable></Input>
                    <Input placeholder="请输入IP" style="width: 210px" v-model="formValidate.vmIP" clearable></Input>
                    <Button type="primary" @click="refreshVmList" style="margin-left:5px">搜索</Button>
                </div>
                <Table border ref="" :columns="columnsVmList" :data="dataVmList"  :stripe="showStripe" :show-header="showHeader" :size="tableSize" style="margin-top:10px" @on-selection-change="getSelectedData"></Table>
                <Page :total="vmTotal"   :current="vmCurrentPage" :page-size="vmItemPage" :show-total= true  @on-change="switchineVmCurrentPage" @on-page-size-change="switchVmItemPage" class-name="pageStyleVm"/> -->
                <!--<FormItem label="属性" >
                    <cusAttribute ref="cusAttribute" @func="getMsgFormSon" v-bind:msgVal="propertiesData" v-if="createFlagTaskModal"></cusAttribute>
                </FormItem>
                <FormItem label="描述" prop="desc" style="margin-top:10px">
                    <Input v-model.trim="formValidate.desc" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入内容" clearable :maxlength="200"></Input>
                </FormItem>-->
            </Form>
        </Modal>
        <Modal
            v-model="taskDeailModal" footer-hide
            title="任务启动详情"
            width = '80'
            >
            <Table ref="" :columns="taskDeailColumns" :data="taskDeailData"  :stripe="showStripe" :show-header="showHeader" :size="tableSize" @on-expand="hostDeail"></Table>
        </Modal>
        </search-table>
</template>
<script>
//import axios from '@/libs/api.request'
// import qgaWriteCollect from '@/components/configer/qgaWriteCollect'
import $ from 'jquery'
import cusAttribute from '@/view/drill_compete/page/cusAttribute'
import {saveoutbandTask,getTaskList,deleteTask,updateTask,amendTask,activeTask,taskDetail,taskDetailHis,hostDetail,getTaskListDetailData,showConfiguration,getDeviceList,loadItemConfiguration,getstatusbyprjid} from '@/api/drill'
import {getaccessgrouplist} from '@/api/access_new'
import {queryTargetAllot,getSceneInfo,queryNetworkList,queryVmWithParty,taskReferee,queryTaskReferee} from '@/api/drill_compete'
import {queryCompanyUsers } from '@/api/users.js'
// import { this.paserTaskStatus } from '@/libs/utils'
import { taskCol } from './task_new/taskMixin';
const validateName = (rule, value, callback) => {
    var myReg = /[~!！@#$%^&*()/\|,<>?"'“‘();:+=\[\]{}]/;
    value = value.replace(/\s*/g,"");
    if(!value){
        callback("请填写名字");
    }else{
        if (myReg.test(value)) {
            callback("名字不能包含特殊字符");
        } else {
            callback();
        }
    }
};

export default {
    name:"flagVm",
    components:{
       //qgaWriteCollect
       cusAttribute
    },
    props:['disabledAllBtn', 'configMode'],
    mixins:[taskCol],
    data(){
        return{
            curPath:this.$route.path,
            tableHeight:'',
            taskConfigerMess:false,
            currentProjectId:"",
            taskTypeTable:'loop_report',
            taskTypeTableTitle:"Flag服务器",
            selectedData:[],
            selectedDataConfiger:[],
            headerData:{
            	serintervalTimeFun:{}
            },
            // amendTaskId:"",
            accessGroupList:[],
            loadingTaskStatusBtn:false,
            columnsData: [
//              {
//                  type: 'selection',
//                  width: 60,
//                  align: 'center',
//                  
//              },
                {
                    title: this.$t('name'),
                    key: 'name',
                    align:'center',
                    placement:'top-left',
                    tooltip:true,
                    width: 240
                },
                {
                    title: '裁判',
                    key: 'referee',
                    align:'center',
                    tooltip:true,
                    width: 100
                },
                // {
                //     title: 'TaskType',
                //     key: 'taskType',
                //      align:'center'
                // },
                // {
                //     title: this.$t('ConfigurationName'),
                //     key: 'configName',
                //     align:'center'
                // },
                // {
                //     title: 'id',
                //     key: 'id',
                //     visible:false
                // },
                {
                    title: this.$t('creatorName'),
                    key: 'creatorName',
                     align:'center',
                    tooltip:true,
                    width: 100
                },
                {
                    title: this.$t('CTime'),
                    key: 'created',
                     align:'center'
                },
                {
                    title:this.$t('Desc'),
                    key:'description',
                    align:'center',
                    tooltip:true,
                    width: 300
                },
                {
                    title: this.$t('Status'),
                    key: 'status',
                    align:'center',
                    width:130,
                    placement:'top-right',
                    render:(h,params)=>{
                        switch (params.row.status) {
                            case "running":
                                return h('Tag',{
                                    props:{
                                        type:'border',
                                        color:'success'
                                    },
                                },'运行中')
                                break;
                            case "error":
                            case "failed":
                                return h('Tag',{
                                    props:{
                                        type:'border',
                                        color:'error'
                                    },
                                },'失败')
                                break;
                            case "completed":
                                return h('Tag',{
                                    props:{
//                                      text:'完成',
                                        type:'border',
                                        color:'primary'
                                    },
                                },'完成')
                                break;
                            case "initialized":
                                return h('Tag',{
                                    props:{
//                                      text:'初始化',
                                        type:'border',
                                        color:'default'
                                    },
                                },'初始化')
                                break;
                            case "starting":
                                return h('Tag',{
                                    props:{
//                                      text:'启动中',
                                        type:'border',
                                        color:'success'
                                    },
                                },'启动中')
                                break;
                            case "closing":
                                return h('Tag',{
                                    props:{
//                                      text:'关闭中',
                                        type:'border',
                                        color:'success'
                                    },
                                },'关闭中')
                                break;
                            default:
                                break;
                        }
                    }

                },
                {
                    title:this.$t('Details'),
                    key:'',
                    align:'center',
                    // minWidth:140,
                    render:(h,params)=>{
                        let statics = params.row.overview;
                        let statusGroup = [];
                        if(JSON.stringify(statics) != "{}"){
                            for(let i in statics){
                                statusGroup.push(h('span',{},this.paserTaskStatus(i)+':'+statics[i]))
                            }
                        }
                        // console.log(statusGroup)
                        return h('div',{},statusGroup)
                    }
                },
                {
                    title:this.$t('operation'),
                    key:'-',
                    align:'center',
                    // width:500,
                    minWidth:350,
                    placement:'top-right',
                    action:true,
                    render:(h,params)=>{
                        let  _this = this;
                        let taskStatus = null
                        let taskBtnType = null
                        let btnStyle = null;
                        if(params.row.taskMode=="normal"){
                            btnStyle = "none"
                        }else{
                            btnStyle = "inline-block"
                        }
                        switch (params.row.status) {
                            case "initialized":
                                taskStatus = "开始"
                                taskBtnType = "success"
                                break;
                            case "error":
                            case "failed":
                                taskStatus = "开始"
                                taskBtnType = "success"
                                break;
                            case "running":
                                taskStatus = "停止"
                                taskBtnType = "error"
                                break;
                            case "completed":
                                taskStatus = "开始"
                                taskBtnType = "success"
                                break;
                            case "starting":
                                taskStatus = "停止"
                                taskBtnType = "error"
                                break;
                            case "closing":
                                taskStatus = "停止"
                                taskBtnType = "error"
                                break;
                             case "stop_error":
                                taskStatus = "停止"
                                taskBtnType = "error"
                                break;
                            default:
                                break;
                        }
                        return h("div",{
                        	attrs:{
                        		class:'btnCenter'
                        	}
                        },[
                            h('Poptip',{
                                props:{
                                    confirm:true,
                                    title:"您确定要删除此任务吗？",
                                    transfer:true
                                },
                                on:{
                                    'on-ok':()=>{
                                        _this.deleteTask(params.row.id)
                                    },
                                    'on-cancel':()=>{

                                    }
                                }
                            },[
                              h('Button',{
                                props:{
                                    type:"text",
                                    size:'small',
                                    disabled:this.disabledAllBtn
                                },
                                attrs:{
                                	title:'删除'
                                },
                                style:{
                                    border:'none',
									background:'none',
									boxShadow:'none',
                                    display: this.configMode === 1 ? 'none':'inline-block'
                                },
                                },[
                                	h('img', {
				                        attrs: {
				//                          src: !this.setReBtnStatus(params.row) ?require('../../../assets/globalIcon/del.png'):require('../../../assets/globalIcon/dis-del.png'),
				                        	src:this.disabledAllBtn ? require('../../../assets/project/delNote-d.png') : require('../../../assets/project/delNote-h.png')
				                        },
				                        style: {
				                            cursor: 'pointer',
//				                            'margin-right':'5px',
				                            'vertical-align': 'middle',
//				                            width:'16px',
//				                            height:'auto',
				                            display:'inline-block',
				                            marginBottom:'4px',
				                        },
				                    })
                                ])]),
                            h('Button',{
                                props:{
                                    type:"text",
                                    size:'small',
                                    disabled:this.disabledAllBtn
                                },
                                attrs:{
                                	title:'修改'
                                },
                                style:{
                                    border:'none',
									background:'none',
									boxShadow:'none',
                                    display: this.configMode === 1 ? 'none':'inline-block'
                                },
                                on:{
                                    click:()=>{
                                        _this.updateTask(params.row.id)
                                    }
                                }
                            },[
                            	h('img', {
					                        attrs: {
					//                          src: !this.setReBtnStatus(params.row) ? require('../../../assets/globalIcon/modify.png'):require('../../../assets/globalIcon/dis-modify2.png'),
					                        	src:this.disabledAllBtn ? require('../../../assets/project/modifys.png') : require('../../../assets/project/modifys-h.png')
					                        },
					                        style: {
					                            cursor: 'pointer',
		//			                            'margin-right':'5px',
					                            'vertical-align': 'middle',
		//			                            width:'16px',
		//			                            height:'auto',
					                            display:'inline-block',
					                            marginBottom:'4px',
					                        },
					                    }),
//					                    h('span',{
//					                        style: {
//					                            cursor: 'pointer',
//					//                          color:!this.setReBtnStatus(params.row) ? '#2d8cf0' : '#c5c8ce'
//																			color:'#2d8cf0'
//					                        },
//					                    },'修改')
                            ]),
                            h('Poptip',{
                                props:{
                                    confirm:true,
                                    title:"您确定要"+taskStatus+"此任务吗？",
                                    transfer:true
                                },
                                on:{
                                    'on-ok':()=>{
                                        _this.activeTask(params.row.id,taskStatus)
                                    },
                                    'on-cancel':()=>{

                                    }
                                }
                            },[
                              h('Button',{
                                props:{
//                                  type:taskBtnType,
									type:"text",
                                    size:'small',
                                    disabled:this.disabledAllBtn || this.loadingTaskStatusBtn,
                                },
                                attrs:{
                                	title:taskStatus+'任务'
                                },
                                style:{
                                    border:'none',
									background:'none',
									boxShadow:'none',
                                    display:btnStyle
                                },
                                },[
                                	h('img', {
				                        attrs: {
				//                          src: !this.setReBtnStatus(params.row) ? require('../../../assets/globalIcon/modify.png'):require('../../../assets/globalIcon/dis-modify2.png'),
				                        	src:taskStatus == '停止' ? (this.disabledAllBtn ? require('../../../assets/scene/dis-stop-task.png') : require('../../../assets/scene/stop-task.png')) : (this.disabledAllBtn ? require('../../../assets/scene/dis-start-task.png') : require('../../../assets/scene/start-task.png'))
				                        },
				                        style: {
				                            cursor: 'pointer',
	//			                          'margin-right':'5px',
				                            'vertical-align': 'middle',
	//			                          width:'16px',
	//			                          height:'auto',
				                            display:'inline-block',
				                            marginBottom:'4px',
				                        },
				                    }),
				                    h('span',{
				                        style: {
				                            cursor: 'pointer',
				//                          color:!this.setReBtnStatus(params.row) ? '#2d8cf0' : '#c5c8ce'
											color:'#2d8cf0'
				                        },
				                    })//,taskStatus+'任务'
                                ])]),
                            //     h('Poptip',{
                            //     props:{
                            //         confirm:true,
                            //         title:"您确定要初始化此任务吗？",
                            //     },
                            //     on:{
                            //         'on-ok':()=>{
                            //             _this.activeTask(params.row.id,"init")
                            //         },
                            //         'on-cancel':()=>{

                            //         }
                            //     }
                            // },[h('Button',{
                            //     props:{
                            //         type:"info",
                            //         size:'small'
                            //     },
                            //     style:{
                            //         margin:'5px'
                            //     },
                            //     },'初始化任务')]),
                                h('Button',{
                                props:{
                                    type:"text",
                                    size:'small'
                                    // style:{margin:'10px'}
                                },
                                style:{
                                    border:'none',
																		background:'none',
																		boxShadow:'none',
                                },
                                on:{
                                    click:()=>{
                                        _this.taskDeail(params.row.id)
                                    }
                                }
                            },[
                            	h('img', {
					                        attrs: {
					//                          src: !this.setReBtnStatus(params.row) ? require('../../../assets/globalIcon/modify.png'):require('../../../assets/globalIcon/dis-modify2.png'),
					                        	src:require('../../../assets/project/magnifier-h.png')
					                        },
					                        style: {
					                            cursor: 'pointer',
		//			                            'margin-right':'5px',
					                            'vertical-align': 'middle',
		//			                            width:'16px',
		//			                            height:'auto',
					                            display:'inline-block',
					                            marginBottom:'4px',
					                        },
					                    }),
					                    h('span',{
					                        style: {
					                            cursor: 'pointer',
					//                          color:!this.setReBtnStatus(params.row) ? '#2d8cf0' : '#c5c8ce'
																			color:'#2d8cf0'
					                        },
					                    })//,'查看详情'
                            ]),
                        ])
                    }

                }
            ],
            taskData: [
                
            ],
            columnsVmList:[
                {
                    type:'selection',
                    width:60,
                    align:'center'
                },
                {
                    title:this.$t('name'),
                    key:'name',
                    align:'center'
                },
                {
                    title:'IP',
                    key:'IP',
                    align:'center',
                    render:(h,params)=>{
                        let value = params.row.IP;
                        let oIP_ = [];
                        $.each(value,(i,item)=>{
                            oIP_.push(h("p",{
                                color:'#000',
                            },item))
                        })
                        return h("div",oIP_)
                    }
                },
                {
                    title:this.$t('SystemType'),
                    key:'sysType',
                    align:'center',
                },
                {
                    title:this.$t('Add'),
                    key:'add',
                    align:'center',
                    width:80,
                    render:(h,params) =>{
                        let _this = params;
                        return h('Button', {
                            props: {
                                type: 'primary',
                            },
                            on:{
                                click: (e) => {
                                    if(this.selectedVmDataTable.indexOf(_this.row.id)!=-1){
                                        this.$Message.info("已添加")
                                        return;
                                    }
                                    // alert('-')
                                    this.addVmAfterTable(_this.row)
                                    this.selectedVmDataTable.push(_this.row.id)
                                    this.formValidate.selectedVmData.push({
                                        "name":_this.row.name,
                                        "id":_this.row.id
                                    })
                                },
                            }
                        }, "+");
                    }
                }
            ],
            dataVmList:[
                
            ],
            selectedVmDataTable:[
                
            ],
            configurationData:[
                
            ],
            createFlagTaskModalLoading:true,
            showBorder: false,
            showStripe: true,
            showHeader: true,
            showIndex: true,
            showCheckbox: false,
            fixedHeader: false,
            tableSize: 'small',
            createFlagTaskModal : false,
            formValidate: {
                name: '',
                configer: '',
                osType:'',
                category:'',
                type:'',
                content:'',
                selectedVmData:[
                    
                ],
                desc: '',
                vmName:'',
                vmIP:'',
                taskMode:'preset',
                access:'true',
                path:'',
                way:'ssh',
                networkArr:'',
                group:[]
            },
            networkArr:'',
            subnetList:[],
            ruleValidate: {
                name: [
                    { required: true, message: '', trigger: 'change',validator:validateName }
                ],
//              taskMode: [
//                 { required: true, message: '', trigger: 'change'}
//              ],
                expireTime: [
                   { required: true,type:'number', message: '', trigger: 'change'}
                ],
                secret: [
                   { required: true, message: '', trigger: 'change'}
                ],
                configer: [
                    { required: true, message: '请选择配置', trigger: 'change'},
                ],
                group:[
                    { required: true, type:"array",min:1,message: '请选择接入组', trigger: 'change'},
                ],
                // selectedVmData:[
                //     // {required:true ,message:"请选择虚拟机"}
                // ],
                desc: [
                    
                ]
            },
            vmCurrentPage:1,
            vmItemPage:10,
            vmTotal:0,
            taskCurrentPage:1,
            taskItemPage:10,
            taskTotal:0,
            judgePanelType:true,//判断是修改还是保存
            workingAreaTaskId:"",//存放修改的任务id

            //查看详情面板
            taskDeailModal:false,
            taskDeailColumns:[
//              {
//                  type:"expand",
//                  width:30,
//                  render: (h, params) => {
//                      return h('div',{},[
//                          h('Row',{props:{class:'expand-row'}},[
//                              h('Col',{props:{span:'8'},style:{width:'50%'}},[
//                                  h('span',{props:{class:'expand-key'}},'宿主机名称:  '),
//                                  h('span',{props:{class:'expand-value'}},params.row.host)
//                              ]),
//                              h('Col',{props:{span:'8'},style:{width:'50%'}},[
//                                  h('span',{props:{class:'expand-key'}},'宿主机ip:  '),
//                                  h('span',{props:{class:'expand-value'}},params.row.hostIp)
//                              ]),
//                          ]),
//                          h('Row',{props:{class:'expand-row'}},[
//                              h('Col',{props:{span:'8'},style:{width:'50%'}},[
//                                  h('span',{props:{class:'expand-key'}},'实例名称:  '),
//                                  h('span',{props:{class:'expand-value'}},params.row.instance)
//                              ]),
//                              h('Col',{props:{span:'8'},style:{width:'50%'}},[
//                                  h('span',{props:{class:'expand-key'}},'ip:  '),
//                                  h('span',{props:{class:'expand-value'}},params.row.IP)
//                              ]),
//                          ]),
//                          h('Row',{props:{class:'expand-row'},},[
//                              h('Col',{props:{span:'8'},style:{width:'50%'}},[
//                                  h('span',{props:{class:'expand-key'}},'cidr:  '),
//                                  h('span',{props:{class:'expand-value'}},params.row.cidr)
//                              ]),
                                // h('Col',{props:{span:'8'},style:{width:'50%'}},[
                                //     h('span',{props:{class:'expand-key'}},'网络名称:  '),
                                //     h('span',{props:{class:'expand-value'}},params.row.networkName)
                                // ]),
//                          ]),
//                      ])
//                  }
//              },
				{
                    title:'id',
                    key:'id',
                    align:'center'
                },
                {
                    title:'用户名',
                    key:'userName',
                    align:'center'
                },
                {
                    title:'接入组id',
                    key:'accessGroupId',
                    align:'center'
                },
                {
                    title:this.$t('Status'),
                    key:'status',
                    align:'center',
                    render:(h,params)=>{
                        return h('span',{}, this.paserTaskStatus(params.row.status))
                    }
                },
//               {
//                  title:this.$t('CTime'),
//                  key:'created',
//                  align:'center'
//              },
//              {
//                  title:this.$t('LastUpdate'),
//                  key:'updated',
//                  align:'center'
//              },
                {
                    title:this.$t('Message'),
                    key:'message',
                    align:'center'
                },
                // {
                //     title:'operation',
                //     key:'-',
                //     align:'center',
                //     render:(h,params)=>{
                //         return h("Button",{
                //             props:{
                //                 type:'primary'
                //             }
                //         },"查看结果")
                //     }
                // }
            ],
            taskDeailData:[],
            
            optionHoverEvent:null,
            optionOutEvent:null,
            configurationInformation:false,
            cardPanelLeft:'3px',
            cardPanelTop:'3px',
            configPanel:{
                configPath:'',
                configSystype:'',
                configContent:'',
                configDescription:'',
                configCreateTime:'',
                configCreatorName:'',
                configName:'',
            },
            hoverCdraBol:false,
            boxShadow:'5px 5px 5px #ddd',
            configerParams:false,//回显配置详细信息
            metadataConfigerInfor:{},
            configerSystype:'',
            currentSceneId:'',
            propertiesData:[],
            vmAttributeData:[],
            deviceList:[],
            currentDevice:[],//设备数据
            peopleValue:[],//人员数据
            currentUsers:[],//保存时数据
            getNameFormId:{},//id和名称对应集合
            userDeciceGroupId:[],//判断是否已经存在
            currentTaskMode:'preset',
            disabledTepBol:false,
            companyUsers:[]
        }
    },
    //props: ['headerData'],
    created(){
         this.currentProjectId = this.$route.query.prjid
         this.currentSceneId = this.$route.query.id
         //this.tableHeight = $(window).height() - 222 ;
        //  this.currentProjectId = "af47d0f5b3964c59a1d5673b85050409"
        //  this.currentProjectId = "c0bf5e6e55734ab59b5f18632c4c9f0a"
        //  localStorage.token = "89bcd9227f6a4f599d2c9c44b310f50f"
        //获取工程详情
        this.getCompanyUsers();
		getstatusbyprjid(this.$route.query.prjid).then(data => {
			if(data.code == 1){
				this.projectInfo = data.attribute;
				this.getProjectSubnet();
			}
		})
        this.getTaskList({
            "testId":this.currentSceneId,
			"page":this.taskCurrentPage,
			"rows":this.taskItemPage,
            "taskType":this.taskTypeTable,
            "taskMode":this.currentTaskMode,
        });
        // this.currentProjectId = this.$route.params.username
    },
    beforeDestroy(){
    	clearInterval(this.headerData.serintervalTimeFun)
    },
    methods: {
        commitTask(){
            let _this = this;
            if(this.peopleValue.length==0){
            	return;
            }
//          if(this.currentDevice.length==0){
//            this.$Message.info("请选择设备")
//            return;
//          }
            for(let i=0;i<this.peopleValue.length;i++){
                let element = _this.peopleValue[i];
                let obj = {};
                obj['accessGroupId'] = element.split(',')[0]
                obj['userId'] = element.split(',')[1]
                obj['testId'] = this.$route.query.id
                _this.currentUsers.push(obj)
                if(_this.userDeciceGroupId.length!=0){
                    if(_this.userDeciceGroupId.indexOf(element.split(',')[0]+','+element.split(',')[1])==-1){
                        _this.userDeciceGroupId.push(element.split(',')[0]+','+element.split(',')[1])
                        _this.formValidate.selectedVmData.push({
                            "name":_this.getNameFormId[element.split(',')[0]] +'/'+_this.getNameFormId[element.split(',')[1]],
                            "id":element.split(',')[0]+','+element.split(',')[1]
                        })
                    }
                }else{
                    _this.userDeciceGroupId.push(element.split(',')[0]+','+element.split(',')[1])
                    _this.formValidate.selectedVmData.push({
                        "name":_this.getNameFormId[element.split(',')[0]] +'/'+_this.getNameFormId[element.split(',')[1]],
                        "id":element.split(',')[0]+','+element.split(',')[1]
                    })
                }
//              for(let j=0;j<_this.currentDevice.length;j++){
//                  let obj = {};
//                  obj['accessGroupId'] = element.split(',')[0]
//                  obj['userId'] = element.split(',')[1]
//                  obj['deviceId'] = _this.currentDevice[j]
//                  _this.currentUsers.push(obj)
//                  if(_this.userDeciceGroupId.length!=0){
//                      if(_this.userDeciceGroupId.indexOf(element.split(',')[0]+','+element.split(',')[1]+','+_this.currentDevice[j])==-1){
//                          _this.userDeciceGroupId.push(element.split(',')[0]+','+element.split(',')[1]+','+_this.currentDevice[j])
//                          _this.formValidate.selectedVmData.push({
//                              "name":_this.getNameFormId[element.split(',')[0]] +'/'+_this.getNameFormId[element.split(',')[1]]+'/'+_this.getNameFormId[_this.currentDevice[j]],
//                              "id":element.split(',')[0]+','+element.split(',')[1]+','+_this.currentDevice[j]
//                          })
//                      }
//                  }else{
//                      _this.userDeciceGroupId.push(element.split(',')[0]+','+element.split(',')[1]+','+_this.currentDevice[j])
//                      _this.formValidate.selectedVmData.push({
//                          "name":_this.getNameFormId[element.split(',')[0]] +'/'+_this.getNameFormId[element.split(',')[1]]+'/'+_this.getNameFormId[_this.currentDevice[j]],
//                          "id":element.split(',')[0]+','+element.split(',')[1]+','+_this.currentDevice[j]
//                      })
//                  }
//              }
            }
//          this.userDeciceGroupId = [];
//          this.formValidate.selectedVmData = [];
//          this.peopleValue = [];
//          this.currentDevice = [];
//          this.networkArr = [];
        },
        getMsgFormSon(data){
            this.propertiesData = data;
        },
        configerManage(){
            this.taskConfigerMess = true
            this.$refs.qgawrite.getQgaWriteInfoList()
        },
        clickEvent: function(){
            // console.log('--')
            // console.log(this.headerData)
            // this.$emit("success",this.taskTypeTableTitle)
            // this.loadConfiguration(this.taskTypeTable)
            // this.loadConfiguration("qga_write")
        },
        handleSelectAll (status) {
            this.$refs.selection.selectAll(status)
        },
        createFlagTask(){
            this.judgePanelType = true
            this.$refs['formValidate'].resetFields();
            this.vmCurrentPage = 1
            this.vmItemPage = 10
            this.formValidate.configer = "";
            this.formValidate.vmName = "";
            this.formValidate.vmIP = "";
            this.formValidate.secret = "";
            this.formValidate.referee = [];
//          this.formValidate.expireTime = "180000";
            this.formValidate.group = [];
            this.peopleValue = [];
            this.configurationData = [];
            this.judgeVmStatus()
            // this.loadConfiguration("qga_write")
            this.propertiesData = [{
                key:null,
                value:null,
            }];
            // this.getVmList({page:this.vmCurrentPage,rows:this.vmItemPage,projectId:this.currentProjectId,order:"asc",sortBy:"name",name:this.formValidate.vmName,ip:this.formValidate.vmIP})
            this.createFlagTaskModal = true;
            // this.formValidate.name = "";
            
            this.formValidate.desc = ""
            // this.selectedVmDataTable = []
            this.selectedVmDataTable = []
            this.formValidate.selectedVmData = []
            this.currentUsers = []//保存时数据
            this.userDeciceGroupId= [];
            this.getAccessUserGroup();
            this.getDeviceList();
			//this.refreshVmList();
        },
        ok(){
            this.handleSubmit('formValidate')
        },
        cancel(){
            //  this.$Message.info('Clicked cancel')
        },
        handleSubmit (name) {
            let $this = this;
            this.properties = {};
            if(this.propertiesData.length!=0){
                let attrData = $this.propertiesData;
                for (let index = 0; index < attrData.length; index++) {
                    const element = attrData[index];
                    if(element.key){
                        $this.properties[element.key] = element.value;
                    }
                }
            }
//          $this.currentUsers = [];
//          JSON.parse($this.formValidate.group).userList.forEach(user => {
//      		users.push({
//          		accessGroupId:$this.formValidate.group.id,
//          		userId:user.userId
//          	});
//      	})
//          $this.formValidate.group.forEach((group,i) => {
//          	let parseGroup = JSON.parse(group);
//          	parseGroup.userList.forEach(user => {
//          		$this.currentUsers.push({
//	            		accessGroupId:parseGroup.id,
//	            		userId:user.userId,
//	            		testId:this.$route.query.id
//	            	});
//          	})
//          })
            $this.$refs[name].validate((valid) => {
                if (valid) {
                    // $this.$Message.success('Success!');
                    if($this.currentUsers.length!=0){
                        if($this.judgePanelType){//判断是保存还是修改
                            $this.saveoutbandTask({
                                name:$this.formValidate.name,
                                // configId:$this.formValidate.configer,
                                description :$this.formValidate.desc,
                                taskMode:$this.formValidate.taskMode,
                                // deviceIdList :$this.selectedVmDataTable,
                                deviceType:"VM",
                                taskType:$this.taskTypeTable,
                                testId:$this.currentSceneId,
//                              users:$this.currentUsers,
								reportUsers:$this.currentUsers,
                                // metadata:{
                                //     users:$this.currentUsers
                                // },
                                properties:$this.properties,
                            })
                        }else{
                            $this.amendTask({
                                name:$this.formValidate.name,
                                description :$this.formValidate.desc,
                                taskMode:$this.formValidate.taskMode,
                                // deviceIdList :$this.selectedVmDataTable,
                                deviceType:"VM",
                                taskType:$this.taskTypeTable,
                                testId:$this.currentSceneId,
                                // metadata:{
                                //     users:$this.currentUsers
                                // },
//                              users:$this.currentUsers,
								reportUsers:$this.currentUsers,
                                properties:$this.properties,
                            })
                        }
                    }else{
                        $this.$Message.info("请选择人员设备")
                        $this.createFlagTaskModalLoading = false;
                        $this.$nextTick(() => {
                            $this.createFlagTaskModalLoading = true;
                        });
                    }

                } else {
                    $this.createFlagTaskModalLoading = false;
                    $this.$nextTick(() => {
                        $this.createFlagTaskModalLoading = true;
                    });
                }
                
            });
        },
        handleReset (name) {
            this.$refs[name].resetFields();
        },
        addVmAfterTable(param){
            let data = this.dataVmList;
            $.each(this.dataVmList,function(i,item){
                if(item.id==param.id){
                    item._checked = true;
                    item._disabled = true;
                }
            })
        },
        handleAdd () {
            // if (this.selectedVmData.length) {
            //     this.selectedVmData.push(this.count[this.count.length - 1] + 1);
            // } else {
            //     this.selectedVmData.push(0);
            // }
        },
        handleClose2 (event, name) {
            // console.log(event)
            console.log(name);
            let $this = this;
            let data = this.formValidate.selectedVmData;
            $this.selectedDataConfiger = [];
            let _data = this.selectedVmDataTable;
            $.each(data,function(i,item){
                if(item){
                    if(item.id==name){
                        data.splice(i,1);
                    }
                }
            });
            $.each(this.userDeciceGroupId,(i,item)=>{
                if(item){
                    if(item==name){
                        this.userDeciceGroupId.splice(i,1);
                    }
                }
            });
            $.each($this.currentUsers,function(i,item){
                console.log(item);
                if(item){
                    console.log(item.accessGroupId+','+item.userId+','+item.deviceId)
                    if(item.accessGroupId+','+item.userId+','+item.deviceId==name){
                        $this.currentUsers.splice(i,1);
                        console.log('--------------')
                    }
                }
            });
        },
        judgeVmStatus(){
            let data = this.dataVmList;
            let data_ = this.selectedVmDataTable
            // console.log(data_)
            //$.each(data,function(i,item){
            data.forEach(function(item,i){
                // console.log(item.id)
                if(data_.indexOf(item.id)!=-1){
                    // alert('-')
                    item._checked = true;
                    item._disabled = true;
                }else{
                    item._checked = false;
                    item._disabled = false;
                }
            })
        },
        loadConfiguration(operation){
            let $this= this;
//          axios({
//              url:this.GLOBAL._projPath_resTasktemplate +"item?"+this.BASE.getParamStr({
//                  "operation":operation
//              }),
//          })
            loadItemConfiguration({ "operation":operation}).then((response)=>{
                $this.configurationData = [];
                if(response.code==1||response.code==0){
                    let ConfigurationList = response.data.list;
                    if(ConfigurationList==""){
                        return;
                    }
                    $.each(ConfigurationList, function(i,item) {
                        $this.configurationData.push({
                            name:item.name,
                            id:String(item.id),
                        })
                    });
                }else{
                    $this.$Message.error(response.prompt)
                }
            })
        },
       getTargetTeamList(){
    		return new Promise((resolve,reject) => {
				let params = {
					pageIndex:1,
					pageSize:2147483647,
					sceneId:this.$route.query.id,
//					projectId:this.$route.query.prjid
				}
//		  		getTargetTeamList_new(params).then(data => {
				queryTargetAllot(params).then(data => {
		  			if(data.code==1){
		  				let targetList = data.data.items || data.data;
		  				resolve(targetList);
		  			}else{
		  				
		  			}
		  		})
	  		})
	  	}, 
	  	getProjectSubnet(){
	    	queryNetworkList(this.$route.query.prjid,this.projectInfo.network.id).then(data => {
	    		if(data.code == 1){
	    			let subnetList = [];
	    			let linkList = [];
	    			data.attribute.editorStage.childs.forEach(item => {
	    				subnetList = subnetList.concat(item.childs);
	    				if(item.links){
	    					linkList = linkList.concat(item.links);
	    				}
	    			})
	    			this.subnetList = subnetList.filter(subnet => subnet.dataType == 'NW');
//	    			this.subnetList.forEach(subnet => {
//	    				let ip;
//	    				if(this.type == 1){
//	    					if(linkList.filter(link => link.bNetid == subnet.id).length > 0){
//	    						ip = linkList.filter(link => link.bNetid == subnet.id)[0].bIpv4;
//	    					}
//	    				}
//						this.idwithName[subnet.id] = {
//							id:subnet.id,
//							name:subnet.name,
//							ip:ip
//						}
//					})
	    		}
	    	})
	    },
        getVmList(getParamObj){
        	return new Promise((resolve,reject) => {
            let $this = this;
//          axios({
//              url: this.GLOBAL._projPath_deploy+'project/servers?'+this.BASE.getParamStr(getParamObj),
//          })
//          getAllVm(getParamObj).then((response)=>{
			queryVmWithParty(this.$route.query.prjid,getParamObj).then((response)=>{
                $this.dataVmList = [];
                if(response.code==1){
                    let vmData = response.data.list;
                    $this.vmTotal = Number(response.data.count);
                    let disabled_ = false;
                    let checked_ = false;
                    this.getTargetTeamList().then(targetList => {
                    	let targetIds = targetList.map(target => target.vmId);
	                    vmData.forEach(function(item,i){
	                        if($this.selectedVmDataTable.length!=0){
	                            if($this.selectedVmDataTable.indexOf(item.id)!=-1){
	                                disabled_ = true
	                                checked_ = true
	                            }else{
	                                disabled_ = false
	                                checked_ = false
	                            }
	                        }else{
	                            disabled_ = false
	                            checked_ = false
	                        }
	                        if(targetIds.includes(item.id)){
	                        	console.log(item.id)
	                        	let networkId = $this.subnetList.filter(subnet => subnet.id == item.networkid)[0].id;
	                        	let networkName = $this.subnetList.filter(subnet => subnet.id == item.networkid)[0].name;
		                        $this.dataVmList.push({
		                            name:item.name,
		                            id:item.id,
		                            sysType:item.sysType,
		                            networkId:networkId,
		                            networkName:networkName,
		                            profile:item.profile = item.profile ? item.profile :'',
		                            IP:item.address.map((item)=>item.ipv4),
		                            _disabled: disabled_,
		                            _checked:checked_,
		
		                        })
		                        $this.getNameFormId[item.id] = networkName +'/'+item.name;
	                        }
	                    })
                    })
                    resolve();
                }
            })
			})
        },
        changeNetwork(networks){
        	this.currentDevice = this.dataVmList.filter(vm => networks.includes(vm.networkId)).map(vm => vm.id);
        },
        switchineVmCurrentPage(numberPage){
            this.vmCurrentPage = numberPage;
//          this.getVmList({page:this.vmCurrentPage,rows:this.vmItemPage,projectId:this.currentProjectId,order:"asc",sortBy:"name",name:this.formValidate.vmName,ip:this.formValidate.vmIP})
        	this.refreshVmList();
        },
        switchVmItemPage(numberSize){
            this.vmItemPage = numberSize
//          this.getVmList({page:this.vmCurrentPage,rows:this.vmItemPage,projectId:this.currentProjectId,order:"asc",sortBy:"name",name:this.formValidate.vmName,ip:this.formValidate.vmIP})
        	this.refreshVmList();
        },
        saveoutbandTask(saveDateJson){
            let $this = this;
//          axios({
//              url:this.GLOBAL._projPath_process+"custom/tasks",
//              method:'post',
//              data:saveDateJson
//          }).
            saveoutbandTask(saveDateJson).then((response)=>{
                if(response.code==1){
                    $this.createFlagTaskModal = false;
                    // 添加成功后清空搜索条件，回退到首页
                    this.taskCurrentPage = 1
                    $this.$Message.success('添加任务成功');
                    $this.getTaskList({
                        "testId":$this.currentSceneId,
                        "page":$this.taskCurrentPage,
                        "rows":$this.taskItemPage,
                        "taskType":$this.taskTypeTable,
                        "taskMode":$this.currentTaskMode,
                    })
                    $this.createFlagTaskModalLoading = false;
                    $this.$nextTick(() => {
                        $this.createFlagTaskModalLoading = true;
                    });
                    this.taskReferee(response.data);
                    //$this.$parent.getStatisticsList();
                }else{
                    $this.$Message.error(response.message);
                    $this.createFlagTaskModalLoading = false;
                    $this.$nextTick(() => {
                        $this.createFlagTaskModalLoading = true;
                    });
                }
            })
        },
        //任务绑定裁判
        taskReferee(task){
        	let params = {
			  "taskId": task.id,
			  "taskName": task.name,
			  "testId": this.$route.query.id,
			  "users": this.formValidate.referee
			};
        	taskReferee(params).then(data =>{
        		if(data.code == 1){
        			console.log('绑定裁判成功');
        		}
        	})
        },
        //查询任务裁判 
        queryTaskReferee(taskId){
        	queryTaskReferee(taskId).then(data => {
        		if(data.code == 1){
        			this.formValidate.referee = data.data.map(user => user.userId);
        		}
        	})
        },
        getTaskList(obj){
            let $this = this;
            clearInterval($this.headerData.serintervalTimeFun)
//          axios({
//              url:this.GLOBAL._projPath_process +"custom/tasks?"+this.BASE.getParamStr(obj),
//          }).
            getTaskList(obj).then((response)=>{
                if(response.code==1){
                    $this.taskTotal = response.data.total;
                    let setintrvalBol = false
                    $this.loadingTaskStatusBtn = false
                    let list = response.data.items.map(async (item, index) => {
                        await queryTaskReferee(item.id).then(data => {
                            if(data.code == 1){
                                item.referee = data.data.map(user => user.userName).join(',')
                            }
                            if($this.selectedData.map((item)=>item.id).join(',').indexOf(item.id)!=-1){
                                item['_checked'] = true;
                            }else{
                                item['_checked'] = false;
                            }
                            if(item.status=="running"||item.status=="starting"||item.status=="closing"){
                                setintrvalBol = true;
                            }
                        })
                        return item
                    })
                    Promise.all(list).then(res => {
                        $this.taskData = res
                        if(setintrvalBol){
                            $this.headerData.serintervalTimeFun  = setTimeout(() => {
                                $this.getTaskList({
                                    "testId":$this.currentSceneId,
                                    "page":$this.taskCurrentPage,
                                    "rows":$this.taskItemPage,
                                    "taskType":$this.taskTypeTable,
                                    "taskMode":$this.currentTaskMode,
                                });
                            }, 2000);
                        }else{
                            clearInterval($this.headerData.serintervalTimeFun)
                        }
                    })
                }else if(response.code==-2){
                    
                }else{
                    $this.$Message.error(response.message)
                }
            })
        },
        switchineTaskCurrentPage(numberPage){
            this.taskCurrentPage = numberPage;
            this.getTaskList({
                "testId":this.currentSceneId,
                "page":this.taskCurrentPage,
                "rows":this.taskItemPage,
                // "configType":"",
                "taskType":this.taskTypeTable,
                "taskMode":this.currentTaskMode,
            })
        },
        switchTaskItemPage(numberSize){
            this.taskItemPage = numberSize
            this.getTaskList({
                "testId":this.currentSceneId,
                "page":this.taskCurrentPage,
                "rows":this.taskItemPage,
                // "configType":"",
                "taskType":this.taskTypeTable,
                "taskMode":this.currentTaskMode,
            })
        },
        deleteTask(taskId){
            let $this = this
//          axios({
//              url:this.GLOBAL._projPath_process +"custom/tasks/"+taskId,
//              method:'delete'
//          }).
            deleteTask(taskId).then((response)=>{
                if(response.code==1){
                    if(response.data[0].code==1){
                        // 删除后展示当前页，当前页没有数据展示前一页
                        this.taskCurrentPage = (this.taskData.length == 1 && this.taskCurrentPage > 1) ?
                            this.taskCurrentPage - 1 : this.taskCurrentPage;
                        $this.getTaskList({
                            "testId":$this.currentSceneId,
                            "page":$this.taskCurrentPage,
                            "rows":$this.taskItemPage,
                            "taskType":$this.taskTypeTable,
                            "taskMode":$this.currentTaskMode,
                        })
                        $this.$Message.success("删除成功")
                        //$this.$parent.getStatisticsList();
                    }else{
                        $this.$Message.error(response.data[0].message)
                    }
                    
                }else{
                    $this.$Message.error(response.data[0].message)
                }
            })
        },
        updateTask(taskId){
            this.judgePanelType = false
            this.formValidate.vmName = "";
            this.formValidate.vmIP = "";
            this.formValidate.group = "";
            this.userDeciceGroupId = [];
            this.currentUsers = [];
            let $this = this ,_this = this;
            this.queryTaskReferee(taskId); //查询任务裁判
//          axios({
//              url:this.GLOBAL._projPath_process +"custom/tasks/"+taskId,
//          }).
            taskDetail(taskId).then((response)=>{
                if(response.code==1){
                    $this.workingAreaTaskId = response.data.id
                    $this.selectedVmDataTable = [];
                    $this.propertiesData = [];
                    $this.currentUsers = [];
                    $this.createFlagTaskModal = true;
                    $this.formValidate.name = response.data.name;
                    $this.formValidate.desc = response.data.description;
                    $this.formValidate.group = [...(new Set(response.data.reportUsers.map( user=> user.accessGroupId)))]
                    // $this.formValidate.expireTime = String(response.data.metadata.expireTime);
                    // $this.formValidate.secret = response.data.metadata.secret;
                    
                    Promise.all([$this.getAccessUserGroup()]).then(data => {
                    	$this.formValidate.group = [...(new Set(response.data.reportUsers.map( user=> user.accessGroupId)))]
                    	$this.formValidate.selectedVmData = [];
                    	if(response.data.reportUsers&&response.data.reportUsers.length!=0){
                            for(let i=0;i<response.data.reportUsers.length;i++){
                                $this.formValidate.selectedVmData.push({
                                    "name":_this.getNameFormId[response.data.reportUsers[i].accessGroupId] +'/'+_this.getNameFormId[response.data.reportUsers[i].userId],
                                    "id":response.data.reportUsers[i].accessGroupId+','+response.data.reportUsers[i].userId
                                })
                                $this.userDeciceGroupId.push(response.data.reportUsers[i].accessGroupId+','+response.data.reportUsers[i].userId)
//                              let obj = {};
//                              obj['accessGroupId'] = response.data.reportUsers[i].accessGroupId
//                              obj['userId'] = response.data.reportUsers[i].userId
//                              obj['testId'] = response.data.reportUsers[i].testId
//                              _this.currentUsers.push(obj)
                            }
                        }
                    })
                    //$this.getAccessUserGroup();
//                  setTimeout(() => {
//                      console.log(_this.getNameFormId)
//                      if(response.data.users&&response.data.users.length!=0){
//                          for(let i=0;i<response.data.users.length;i++){
//                              $this.formValidate.selectedVmData.push({
//                                  "name":_this.getNameFormId[response.data.users[i].accessGroupId] +'/'+_this.getNameFormId[response.data.users[i].userId]+'/'+_this.getNameFormId[response.data.users[i].deviceId],
//                                  "id":response.data.users[i].accessGroupId+','+response.data.users[i].userId+','+response.data.users[i].deviceId
//                              })
//                              $this.userDeciceGroupId.push(response.data.users[i].accessGroupId+','+response.data.users[i].userId+','+response.data.users[i].deviceId)
//                              let obj = {};
//                              obj['accessGroupId'] = response.data.users[i].accessGroupId
//                              obj['userId'] = response.data.users[i].userId
//                              obj['deviceId'] = response.data.users[i].deviceId
//                              _this.currentUsers.push(obj)
//                          }
//                      }
//                  }, 1500);
                    // if(response.data.metadata){
                    //     // $this.configerParams = true;
                    //     $this.formValidate.category = response.data.metadata.category ?  response.data.metadata.category: ''
                    //     $this.formValidate.path = response.data.metadata.path ? response.data.metadata.path:''
                    //     $this.formValidate.type = response.data.metadata.type ? response.data.metadata.type:''
                    //     $this.formValidate.content = response.data.metadata.content ? response.data.metadata.content: ''
                    //     $this.formValidate.osType = response.data.metadata.osType ? response.data.metadata.osType :''
                    //     $this.metadataConfigerInfor =  response.data.metadata;
                    // }
                    // $this.getVmList({page:$this.vmCurrentPage,rows:$this.vmItemPage,projectId:$this.currentProjectId,order:"asc",sortBy:"name",name:$this.formValidate.vmName,ip:$this.formValidate.vmIP,sysType:$this.configerSystype})
                    // if(response.data.deviceData.length!=0){
                    //     $.each(response.data.deviceData,function(i,item){
                    //         $this.selectedVmDataTable.push(item.deviceId);
                    //         $this.formValidate.selectedVmData.push({
                    //             name:item.deviceName,
                    //             id:item.deviceId
                    //         })
                    //     })
                    // }
                    $this.formValidate.taskMode = response.data.taskMode;
                    if(JSON.stringify(response.data.properties)!="{}"){
                        for(let i in response.data.properties){
                            let obj = {};
                            obj['key'] = i;
                            obj['value'] = response.data.properties[i];
                            $this.propertiesData.push(obj)
                        }
                    }
                }else{
                    $this.workingAreaTaskId = ""//清空任务id
                    $this.$Message.error(response.message)
                }
            }).then(()=>{
                //$this.loadConfiguration("qga_write")
                // $this.getVmList({page:this.vmCurrentPage,rows:this.vmItemPage,projectId:this.currentProjectId,order:"asc",sortBy:"name",name:this.formValidate.vmName,ip:this.formValidate.vmIP})
                $this.judgeVmStatus()
            })
        },
        amendTask(amendTaskData){
            let $this = this;
//          axios({
//              url:this.GLOBAL._projPath_process+"custom/tasks/"+this.workingAreaTaskId,
//              method:'put',
//              data:amendTaskData
//          })
            amendTask(this.workingAreaTaskId,amendTaskData).then((response)=>{
                if(response.code==1){
                    $this.createFlagTaskModal = false;
                    $this.$Message.success("修改成功");
                    $this.getTaskList({
                        "testId":$this.currentSceneId,
                        "page":$this.taskCurrentPage,
                        "rows":$this.taskItemPage,
                        "taskType":$this.taskTypeTable,
                        "taskMode":$this.currentTaskMode,
                    })
                    $this.createFlagTaskModalLoading = false;
                    $this.$nextTick(() => {
                        $this.createFlagTaskModalLoading = true;
                    });
                    let task = {
                    	id:this.workingAreaTaskId,
                    	name:amendTaskData.name
                    }
                    this.taskReferee(task);
                }else{
                    $this.$Message.error(response.message)
                    $this.createFlagTaskModalLoading = false;
                    $this.$nextTick(() => {
                        $this.createFlagTaskModalLoading = true;
                    });
                }
            })
        },
        activeTask(taskId,active){
            let active_cn = active
            this.loadingTaskStatusBtn = true
            let $this = this
            if(active=="开始"){
                active = "start"
            }else if(active=="停止"){
                active = "stop"
            }
//          axios({
//              url:this.GLOBAL._projPath_process +"custom/tasks/"+taskId+'/execute?operation='+active,
//              method:'post'
//          }).
            activeTask(taskId,active).then((response)=>{
                let activeType;
                if(response.code==1){
                    // 延时一秒在请求getTaskList , 避免修改了状态，接口还没返回就去请求列表 导致偶现状态没变化
                    setTimeout(()=>{
                        $this.getTaskList({
                            "testId":$this.currentSceneId,
                            "page":$this.taskCurrentPage,
                            "rows":$this.taskItemPage,
                            "taskType":$this.taskTypeTable,
                            "taskMode":$this.currentTaskMode,
                        });
                        $this.$Message.success(active_cn+"任务成功")
                },1000)
                }else{
                    $this.loadingTaskStatusBtn = false
                    $this.$Message.error(response.message)
                }
            })
        },
        taskDeail(taskId){
            let $this = this
//          axios({
//              url:this.GLOBAL._projPath_process +"custom/tasks/"+taskId+'/histories',
//          }).
            taskDetailHis(taskId).then((response)=>{
                if(response.code==1){
                    $this.taskDeailData = response.data;
                    $this.taskDeailModal = true
                    // $this.taskDeailData= reponse.data;
//                  $.each(response.data,function(i,item){
//                      $this.taskDeailData.push({
//                          deviceName:item.deviceName,
//                          status:item.status,
//                          message:item.message,
//                          deviceId:item.deviceId,
//                          host:'',
//                          hostIp:'',
//                          instance:'',
//                          osId:'',
//                          IP:'',
//                          cidr:'',
//                          created:item.created ? item.created:'',
//                          updated:item.updated ? item.updated:'',
//                          _expanded:false
//                      })
//                  })
                }else{
                    $this.$Message.error(response.message)
                }
            })
        },
        getSelectedTableItem(selection){
            this.selectedData = [];
            this.selectedData = selection
            
            console.log(selection)
        },
        hostDeail(row){
            console.log(row.deviceId);
            let $this  = this;
            if(!row._expanded){
//              axios({
//                  url:this.GLOBAL._projPath_deploy+"project/servers/"+row.deviceId,
//              }).
                hostDeail(row.deviceId).then((response)=>{
                    if(response.code==1){
                        $.each($this.taskDeailData,function(i,item){
                            if(row.deviceId==item.deviceId){
                                item._expanded = true
                                item.host = response.data.host;
                                item.hostIp = response.data.hostIp;
                                item.instance = response.data.instance;
                                item.osId= response.data.osId;
                                item.IP = response.data.addresses.map((item)=> item.ip)
                                item.cidr = response.data.addresses.map((item)=> item.cidr)
                                return false;
                            }
                        })
                    }
                })
            }else{
                row._expanded = !row._expanded;
            }
        },
        // setintervalTaskList(obj){
        //     let $this = this;
        //     $.ajax({
        //         type:"get",
        //         url:_projPath_process +"custom/tasks?"+GlobalTool.getParamStr(obj),
        //         async:true,
        //         dataType:"json",
        //         headers:{"Authorization":localStorage.token},
        //         contentType:"application/json",
        //         success:function(reponse){
        //             if(reponse.code==1){
        //                 if(reponse.data.list.length!=0){
        //                     $.each(reponse.data.list,function(i,item){

        //                     })
        //                     $this.taskData = reponse.data.list;
        //                 }
        //             }else if(reponse.code==-2){
                        
        //             }else{
        //                 $this.$Message.error(response.message)
        //             }
        //         },
        //         error:function(){
        //             $this.$Message.error(errorMessage)
        //         }
        //     });
        // },
        refreshTaskList(){
            this.getTaskList({
                "testId":this.currentSceneId,
                "page":this.taskCurrentPage,
                "rows":this.taskItemPage,
                "taskType":"",
                "taskMode":this.currentTaskMode,
            });
        },
        refreshVmList(){
        	let params = {
        		page:this.vmCurrentPage,
                rows:this.vmItemPage,
                projectId:this.currentSceneId,
                order:"asc",
                sortBy:"name",
                name:this.formValidate.vmName,
                ip:this.formValidate.vmIP,
                profile:this.profileValue,
                findPorts:true
        	}
        	if(this.formValidate.networkId){
        		params.networkId = this.formValidate.networkId;
        	}
//      	this.refreshVmList();
            this.getVmList(params);
        },
        getTaskListDeailData(){
            let $this = this
//          axios({
//              url:this.GLOBAL._projPath_process +"overview/task/countByStatus?"+this.BASE.getParamStr({
//                  "testId":$this.currentSceneId,
//                  "taskType":$this.taskTypeTable,
//                  "node":"false"
//              }),
//          })
            let params = {
            	"testId":$this.currentSceneId,
                "taskType":$this.taskTypeTable,
                "node":"false"
            }
            getTaskListDetailData(params).then((response)=>{
                if(response.code==1){
                    let _s = 0,_e = 0,_i = 0,_r = 0,stintervalBol = false;
                    _s = response.data.completed;
                    _e = response.data.error;
                    _i = response.data.initialized;
                    _r = Number(response.data.running)+Number(response.data.starting)+Number(response.data.closing);
                    if(_r!=0){
                        stintervalBol = true;
                    }
                    $this.$emit("success",$this.taskTypeTableTitle+'-'+_s+'-'+_e+'-'+_i+'-'+_r+'-'+stintervalBol+'-'+$this.taskCurrentPage+'-'+$this.taskItemPage)
                }else if(response.code==-2){
                    
                }else{
                    $this.$Message.error(response.message)
                }
            })
        },
        setintervalTaskList(){
            // alert('-')
            let $this = this;
//          axios({
//              url:this.GLOBAL._projPath_process +"custom/tasks?"+this.BASE.getParamStr({
//                  "testId":this.currentSceneId,
//                  "page":this.taskCurrentPage,
//                  "rows":this.taskItemPage,
//                  "taskType":this.taskTypeTable,
//                  "node":"false"
//              }),
//          })
            let params = {
            	"testId":this.currentSceneId,
                "page":this.taskCurrentPage,
                "rows":this.taskItemPage,
                "taskType":this.taskTypeTable,
                "node":"false"
            }
            getTaskList(params).then((response)=>{
                if(response.code==1){
                    $this.taskData = [];
                    if(response.data.list.length!=0){
                        let stintervalBol  = false
                        $this.taskData = response.data.list
                        $.each(response.data.list,function(i,item){
                            if(item.status=="running"||item.status=="starting"||item.status=="closing"){
                                stintervalBol = true
                            }
                            $this.taskData[i].status = item.status;
                        })
                        if(!stintervalBol){
                            clearInterval($this.headerData.serintervalTimeFun)
                        }
                    }
                    $this.getTaskListDeailData()
                }else if(response.code==-2){
                    
                }else{
                    $this.$Message.error(response.message)
                }
            })
        },
        addSelectedData(){
            let that = this,bol = true;
            $.each(that.selectedDataConfiger,function(i,item){
                console.log(item)
                if(that.selectedVmDataTable.indexOf(item.id)!=-1){
                    
                }else{
                    bol = false
                    that.addVmAfterTable(item)
                    that.selectedVmDataTable.push(item.id)
                    that.formValidate.selectedVmData.push({
                        "name":item.name,
                        "id":item.id
                    })
                }
            })
            if(bol){
                that.$Message.info("请选择要添加的内容")
            }
        },
        getSelectedData(selection){
            // console.log(selection)
            this.selectedDataConfiger = [];
            this.selectedDataConfiger = selection;
        },
        /**
         * @description: 鼠标移上配置显示详情
         * @param {type} 
         * @return: 
         */
        mouseOverConfiger(e,value){
            clearTimeout(this.optionHoverEvent)
            let _this = this;
            this.optionHoverEvent = setTimeout(() => {
                if(this.hoverCdraBol){
                    return;
                }
                this.configurationInformation = true
                this.cardPanelLeft = e.layerX +30+ 'px'
                this.cardPanelTop = e.layerY +35+'px'
                //查询配置详细信息
//              axios({
//                  url: '/tasktemplate/item/' + value,
//                  method: 'get',
//              })
                showConfiguration(value).then(function (response) {
                    if(response.code != '1'){
                        _this.$Message.warning(response.prompt);
                    }else{
                        _this.configPanel.configName = response.data.name
                        _this.configPanel.configPath = response.data.data.path
                        _this.configPanel.configSystype = response.data.data.osType
                        _this.configPanel.configContent = response.data.data.content
                        _this.configPanel.configDescription = response.data.description
                        _this.configPanel.configCreateTime = response.data.createTime
                        _this.configPanel.configCreatorName = response.data.creatorName
                        
                    }
                });
            }, 300);
        },
        mouseLeaveConfiger(ev,value){
            clearTimeout(this.optionOutEvent)
            this.optionOutEvent = setTimeout(() => {
                if(!this.hoverCdraBol){
                    this.configurationInformation = false
                    this.cardPanelLeft = '0'
                    this.cardPanelTop = '0'
                }
            }, 300);
        },
        showConfiguration(value){
            this.configurationInformation = false
            this.selectedVmDataTable = [];
            this.formValidate.selectedVmData = [];

            let _this = this;
            if(value){
//              axios({
//                  url: '/tasktemplate/item/' + value,
//                  method: 'get',
//              }).
                showConfiguration(value).then(function (response) {
                    if(response.code != '1'){
                        _this.$Message.warning(response.prompt);
                        _this.configerParams = false;
                    }else{
                        // _this.configerParams = true;
                        _this.formValidate.category = response.data.category ?  response.data.category: ''
                        _this.formValidate.path = response.data.data.path ? response.data.data.path:''
                        _this.formValidate.type = response.data.data.type ? response.data.data.type:''
                        _this.formValidate.content = response.data.data.content ? response.data.data.content: ''
                        _this.formValidate.osType = response.data.data.osType ? response.data.data.osType :''
                        _this.metadataConfigerInfor =  response.data.data;
                        _this.configPanel.configName = response.data.name;
                        _this.metadataConfigerInfor['configurationName'] = response.data.name;
                        _this.configerSystype = response.data.data.osType;
//                      _this.getVmList({page:_this.vmCurrentPage,rows:_this.vmItemPage,projectId:_this.currentProjectId,order:"asc",sortBy:"name",name:_this.formValidate.vmName,ip:_this.formValidate.vmIP,sysType:_this.configerSystype})
						_this.refreshVmList();
                    }
                });
            }else{
                _this.configerParams = false;
                _this.formValidate.category = ""
                _this.formValidate.path = ""
                _this.formValidate.type = ""
                _this.formValidate.content = ""
                _this.formValidate.osType = ""
                _this.configerSystype = "";
//              _this.getVmList({page:_this.vmCurrentPage,rows:_this.vmItemPage,projectId:_this.currentProjectId,order:"asc",sortBy:"name",name:_this.formValidate.vmName,ip:_this.formValidate.vmIP,sysType:_this.configerSystype})
            	_this.refreshVmList();
            }
        },
        jinru(e){
            this.hoverCdraBol = true
        },
        yichu(e){
            this.hoverCdraBol = false
            this.configurationInformation = false
            this.cardPanelLeft = '0'
            this.cardPanelTop = '0'
        },
        ddd(e){
            e.preventDefault()
            e.stopPropagation();
        },
        overStyle(){
            this.boxShadow = '5px 5px 5px #ddd'
        },
        removeStyle(){
            this.boxShadow = ''
        },
        getAccessUserGroup(){
          return new Promise((resolve,reject) => {
            let _this = this;
            _this.getNameFormId = {};
            _this.vmAttributeData = [];
//          axios({
//              url:'process/accessGroups?&testId='+this.currentSceneId+'&pageIndex=1&pageSize=1000&order=asc&property=name',
//          }).
            let params = {
            	testId:this.currentSceneId,
            	pageIndex:1,
            	pageSize:1000,
            	order:'asc',
            	property:'name'
            }
            getaccessgrouplist(params).then((response)=>{
                if (response.code==1) {
                	this.accessGroupList = response.data.items;
                    let data = response.data.items;
                    for (let index = 0; index < data.length; index++) {
                        const element = data[index];
                        _this.getNameFormId[element.id] = element.name
                        for(let j=0;j<element.userList.length;j++){
                            let elements = element.userList[j];
//                          let obj = {};
//                          obj['name'] = element.name
//                          obj['id'] = element.id;
//                          obj['userId'] = elements.userId;
//                          obj['userName'] = elements.userName;
                            _this.getNameFormId[elements.userId] = elements.userName
                            //_this.vmAttributeData.push(obj)
                        }
                    }
                    resolve();
                    //this.getDeviceList()
                } else {
                    this.$Message.error(response.message)
                }
            })
          })
        },
        getAccessGroupMember(ids){
        	this.formValidate.selectedVmData = [];
    		this.peopleValue = [];
    		this.currentUsers = [];
    		this.userDeciceGroupId = [];
        	if(ids.length == 0){
        		return
        	}
        	ids.forEach(id => {
        		let element = this.accessGroupList.filter(group => group.id == id)[0];
	        	for(let j=0;j<element.userList.length;j++){
	                let elements = element.userList[j];
	                let obj = {};
	                obj['name'] = element.name
	                obj['id'] = element.id;
	                obj['userId'] = elements.userId;
	                obj['userName'] = elements.userName;
	                //_this.getNameFormId[elements.userId] = elements.userName
	                this.vmAttributeData.push(obj)
	            }
	        	this.networkArr = [];
	        	this.peopleValue = this.peopleValue.concat(element.userList.map(user => {
	        		return element.id + ',' + user.userId
	        	}))
	        	this.peopleValue = [...new Set(this.peopleValue)]
        	})
//      	let element = this.accessGroupList.filter(group => group.id == id)[0];
//      	for(let j=0;j<element.userList.length;j++){
//              let elements = element.userList[j];
//              let obj = {};
//              obj['name'] = element.name
//              obj['id'] = element.id;
//              obj['userId'] = elements.userId;
//              obj['userName'] = elements.userName;
//              //_this.getNameFormId[elements.userId] = elements.userName
//              this.vmAttributeData.push(obj)
//          }
//      	this.networkArr = [];
//      	this.peopleValue = element.userList.map(user => {
//      		return element.id + ',' + user.userId
//      	})
        	this.commitTask();
        },
        //查询场景下的特征码服务器列表
        getDeviceList(){
          return new Promise((resolve,reject) => {
            let _this = this;
//          axios({
//              url:'process/tests/'+this.currentSceneId+'/flag/devices',
//              method:'get',
//          }).
//          let params = {
//          	page:1,
//          	pageSize:100000,
//          	sortBy:name,
//          	order:'asc',
//          	findPorts:false
//          };
//          getDeviceList(_this.currentProjectId,params).then((response)=>{
//              if (response.code==1) {
//                  this.deviceList = response.data.list;
//                  for(let i=0;i<response.data.list.length;i++){
//                      _this.getNameFormId[response.data.list[i].id] = response.data.list[i].name
//                  }
//                  resolve();
//              } else {
//                  this.$Message.error(response.message)
//              }
//          })
            let params = {
				pageIndex:1,
				pageSize:2147483647,
				sceneId:this.$route.query.id,
//				subnetId:this.formValidate.networkId
//				projectId:this.$route.query.prjid
			}
	  		queryTargetAllot(params).then(data => {
	  			if(data.code==1){
//	  				this.targetTeamData = data.data.items || data.data;
//	  				resolve();
					this.deviceList = data.data.items || data.data;
					this.deviceList.forEach(device => {
						device.id = device.vmId;
						device.name = device.vmName;
					})
					for(let i=0;i<data.data.items.length;i++){
                        _this.getNameFormId[data.data.items[i].vmId] = data.data.items[i].subnetName+'/'+data.data.items[i].vmName
                    }
					resolve();
	  			}else{
	  				this.$Message.error(data.message)
	  			}
	  		})
          })
        },
        getCompanyUsers(){
	     	let params = {
	     	 	pageIndex:1,
	     	 	pageSize:2147483646,
	     	 	order:'desc',
	     	 	sortBy:'created',
	     	 	role:'referee'
	     	};
	     	queryCompanyUsers(params).then(data => {
	     	 	if(data.code == 1){
	     	 		 this.companyUsers = data.data.items;
	     	 	}else{
	     	 		
	     	 	}
	     	})
	    },
    },
    watch:{
        listenParam(){
            // console.log(this.buttonsName)
        }
    }
}

</script>


